package com.li.xishushuzu;

public class SpareArray {
    public static void main(String[] args) {
        int chreesArray[][] = new int[11][11];
        chreesArray[1][2] = 1;
        chreesArray[2][3] = 2;
        System.out.println("原始的二维数组");
        for (int[] rows : chreesArray) {
            for (int data : rows) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
        //遍历，得到非零的个数
        int sum = 0;
        for (int[] rows : chreesArray) {
            for (int data : rows) {
                if (data != 0) {
                    sum++;
                }
            }
        }


        System.out.println(sum);
        //创建稀疏数组
        int sparseArray[][] = new int[sum + 1][3];
        //给稀疏数组赋值
        sparseArray[0][0] = 11;
        sparseArray[0][1] = 11;
        sparseArray[0][2] = sum;
        int count = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chreesArray[i][j] != 0) {
                    count++;
                    sparseArray[count][0] = i;
                    sparseArray[count][1] = j;
                    sparseArray[count][2] = chreesArray[i][j];
                }
            }
        }
        //输出稀疏数组
        System.out.println("得到的稀疏数组");
        for (int i = 0; i < sparseArray.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n", sparseArray[i][0], sparseArray[i][1], sparseArray[i][2]);
        }
        int cherryArray2[][] = new int[sparseArray[0][0]][sparseArray[0][1]];
        for (int i = 1; i < sparseArray.length; i++) {
            cherryArray2[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }
        System.out.println("得到的为");
        for (int[] rows : cherryArray2) {
            for (int data : rows) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }


    }
}
